package com.jinwei.qunguanjia.security.handler;

import com.jinwei.qunguanjia.common.core.domain.Response;
import com.jinwei.qunguanjia.common.enums.HttpResponseEnum;
import com.jinwei.qunguanjia.common.utils.JsonUtils;
import com.jinwei.qunguanjia.common.utils.ServletUtils;
import com.jinwei.qunguanjia.common.utils.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证失败处理类 返回未授权
 * 
 * @author yuanzs
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderString(response, JsonUtils.toJsonString(Response.fail(HttpResponseEnum.UNAUTHORIZED.getCode(), msg)));
    }
}
